<template>
    <div>
        <div class="app-container flex-box">
            <div class="input-form">
                <el-dialog :visible.sync="bigImageVisible">
                    <img width="100%" :src="bigImageUrl" alt="">
                </el-dialog>

                <el-form :rules="formRules" ref="dataForm" :model="bean" label-position="right" label-width="100px"
                         style='width: 1000px; margin-left:50px;'>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="单位名称" prop="name">
                                <el-input v-model="bean.name" placeholder="输入单位名称"></el-input>
                            </el-form-item>
                            <el-form-item label="单位logo" prop="logo">
                                <el-upload action="" :http-request="onUploadTopImg" :show-file-list="false"
                                           list-type="picture-card" :before-upload="beforeUpload">
                                    <img v-if="bean.logo" :src="bean.logo" class="img">
                                    <i v-else class="el-icon-plus img-uploader-icon"></i>
                                </el-upload>
                            </el-form-item>
                            <el-form-item label="所属行业" prop="industry">
                                <el-select v-model="bean.industry" placeholder="请选择所属行业">
                                    <el-option v-for="item in this.basedata.industry" :key="item.data_value"
                                               :label="item.data_text"
                                               :value="item.data_value"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="人数规模" prop="scale">
                                <el-select v-model="bean.scale" placeholder="请选择人数规模">
                                    <el-option v-for="item in this.basedata.company_scale" :key="item.data_value"
                                               :label="item.data_text"
                                               :value="item.data_value"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="单位网址" prop="website">
                                <el-input v-model="bean.website" placeholder="输入单位网址"></el-input>
                            </el-form-item>
                            <el-form-item label="单位地址" prop="address">
                                <el-input v-model="bean.address" placeholder="选择单位地址"
                                          @focus="openAddressWin"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">

                            <el-form-item label="单位简介" prop="description">
                                <el-input v-model="bean.description" placeholder="填写单位简介" type="textarea"
                                          :autosize="{ minRows: 4, maxRows: 20}"></el-input>
                            </el-form-item>
                            <el-form-item label="单位环境" prop="">
                                <div class="tips">最多可以上传9张图品，每张大小不可超过100KB。</div>
                                <el-upload action="" :http-request="onUploadBottomImgs" :show-file-list="true"
                                           :multiple="true" :limit="9" :on-exceed="uploadBottomExceed"
                                           list-type="picture-card"
                                           :file-list="imgs" :before-upload="beforeUpload"
                                           :on-preview="showBigImg" :on-remove="onRemoveBottom">
                                    <i class="el-icon-plus"></i>
                                </el-upload>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
        </div>
        <el-button type="primary" @click="doSubmit" :loading="dealing"
                   style="width:240px;margin:20px auto;display:block;">保存
        </el-button>
        <addressMapPicker @addressDialogClose="addressDialogClose" v-if="addressDialogVisible" :address_id="bean.address_id"></addressMapPicker>
    </div>
</template>
<script>
	import waves from '@/directive/waves' // 水波纹指令
	import API from '@/api'
	import Http from '@/http'
	import Store from '@/store'
	import Msg from '@/utils/msg'
	import Utils from '@/utils/common'
	import Validator from '@/utils/validate'
	import Auth from '@/auth'
	import _ from 'underscore'
	import Qiniu from '@/utils/qiniu'
	import {mapGetters} from 'vuex'
	import addressMapPicker from '@/components/addressMapPicker'

	export default {
		directives: {waves},
		data() {
			return {
				bigImageUrl: '',
				bigImageVisible: false,
				formRules: {
					name: [{required: true, message: '请填写单位名称', trigger: 'blur'}],
				},
				dialogParamVisible: false,
				dealing: false,
				bean: {},
				imgs:[],
				addressDialogVisible: false
			}
		},
		computed: {
			...mapGetters([
				'basedata',
			]),
		},
		components: {
			addressMapPicker
		},
		created() {
			var unit_id = this.$route.query.unit_id
			if (unit_id) {
				Http.getModel(API.get_dept, {id:unit_id}, false).then((json) => {
					this.dealing = false
					if (json.code == 0) {
						let bean = json.data;
						let imgs_arr = []
						if (bean.img_list) {
							imgs_arr = bean.img_list.split(",");
						}
						let imgs_arr_obj = []
						for (var i = 0; i < imgs_arr.length; i++) {
							imgs_arr_obj.push({url: imgs_arr[i]})
						}
						this.imgs = imgs_arr_obj;
						this.bean = bean;
					} else {
						Msg.error(json.msg)
					}
				})
			}
		},
		methods: {
			openAddressWin() {
				this.addressDialogVisible = true
			},
			addressDialogClose(address,address_id){
				this.addressDialogVisible = false
				if(address){
					this.bean.address = address
					this.bean.address_id = address_id
				}
			},
			doSubmit() {
				this.$refs['dataForm'].validate((valid) => {
					if (valid) {
						this.dealing = true

						let img_arr = []
						for (let i = 0; i < this.imgs.length; i++) {
							img_arr.push(this.imgs[i].url)
						}
						this.bean.img_list = img_arr.join(",")
						Http.getModel(API.save_dept, this.bean, false).then((json) => {
							this.dealing = false
							if (json.code == 0) {
								Msg.success(json.msg, () => {
									let auth_token = Store.getters.token
									if (!Validator.isEmpty(auth_token)) {
										Auth.getUserByToken(auth_token).then((json) => {
											if (json.code == 0) {
												let user = json.data
												Store.commit("SET_USER", user)
												Store.commit("SET_COMPANY", user.company)
											}
										})
									}
									this.$router.back();
									var view = {
                    name: "unitEdit",
                    path: "/unit/editor",
                    title: "unitEdit"
                  }
                  this.$store.dispatch('delVisitedViews', view).then((views) => {})
								})
							} else {
								Msg.error(json.msg)
							}
						})
					}
				})
			},
			onUploadTopImg(obj) {
				new Qiniu().upload(obj.file, (url) => {
					console.log("url:", url);
					this.$set(this.bean,'logo',url);
					console.log('this.bean:', this.bean)
				})
			},
			onUploadBottomImgs(obj) {
				new Qiniu().upload(obj.file, (url) => {
					this.imgs.push({url: url})
				})
			},
			uploadBottomExceed() {
				Msg.error("最多只能传9张图片！")
			},
			onRemoveBottom(a, list) {
				this.bean.img_list = list
			},
			beforeUpload(file) {
				let result = true;
				let index = _.indexOf(['image/jpeg', 'image/jpg', 'image/png'], file.type);
				if (index < 0) {
					Msg.error('上传图片只能是 jpg 或 png 格式!');
					result = false;
				}
				if ((file.size / 1024 / 1024) > 0.1) {
					Msg.error('上传图片大小不能超过 100KB!');
					result = false;
				}
				return result;
			},
			showBigImg(file) {
				this.bigImageUrl = file.url;
				this.bigImageVisible = true;
			}
		}
	}
</script>
<style lang="scss" rel="stylesheet/scss" scoped>
    .top-imgs-ct {
        img {
            display: inline-block;
        }
    }

    .flex-box {
        display: flex;
        .input-form {
            flex: 1
        }
        .upload-form {
            flex: 1
        }
    }

    .el-select, .el-cascader--medium {
        width: 100%;
    }

    .img, video {
        width: 146px;
        height: 146px;
    }
</style>
